import os
import shutil
import re
import pandas as pd
import configparser
import sys


def sanitize_filename(filename):
    """清理文件名中的特殊字符"""
    return re.sub(r'[\\/*?:"<>|]', "", filename)


def save_config(input_folder, output_folder, archive_folder):
    config = configparser.ConfigParser()
    config['Paths'] = {
        'input_folder': input_folder,
        'output_folder': output_folder,
        'archive_folder': archive_folder
    }
    with open('config.ini', 'w') as configfile:
        config.write(configfile)


def get_config_paths():
    config = configparser.ConfigParser()
    config.read('config.ini')

    if 'Paths' not in config or 'input_folder' not in config['Paths'] or 'output_folder' not in config['Paths'] or 'archive_folder' not in config['Paths']:
        print("配置文件中缺少输入、输出和归档文件夹路径。请手动编辑 config.ini 文件以添加这些路径。")
        input_folder = input("选择输入文件夹路径: ")
        output_folder = input("选择输出文件夹路径: ")
        archive_folder = input("选择归档文件夹路径: ")
        save_config(input_folder, output_folder, archive_folder)
    else:
        input_folder = config['Paths']['input_folder']
        output_folder = config['Paths']['output_folder']
        archive_folder = config['Paths']['archive_folder']

    return input_folder, output_folder, archive_folder


def process_files(input_folder, output_folder):
    # 确保输出文件夹存在
    os.makedirs(output_folder, exist_ok=True)

    # 遍历输入文件夹中的所有文件
    for filename in os.listdir(input_folder):
        if filename.endswith(".xlsx"):
            # 构造完整的文件路径
            file_path = os.path.join(input_folder, filename)

            try:
                # 提取第1行第20列的数据（注意：pandas的索引是从0开始的）
                df = pd.read_excel(file_path, engine='openpyxl', header=None, nrows=1)
                name = df.iloc[0, 19]

                # 提取RTS之前的部分
                rts_index = str(name).find("RTS")
                if rts_index != -1:
                    name = str(name)[:rts_index].strip()

                # 清理文件名中的特殊字符
                sanitized_name = sanitize_filename(str(name))
                new_filename = f"{sanitized_name}_{filename}"
                new_file_path = os.path.join(output_folder, new_filename)

                # 直接复制文件以保留格式和内容
                shutil.copy(file_path, new_file_path)
                print(f"Copied to: {new_file_path}")

                # 检查文件大小
                if os.path.exists(new_file_path):
                    file_size = os.path.getsize(new_file_path)
                    print(f"File size: {file_size} bytes")
                else:
                    print(f"Error: File not created at {new_file_path}")

                # 构造同名的csv和pdf文件名
                base_name = new_filename[:-5]  # 去掉.xlsx后缀
                csv_filename = f"{base_name}.csv"
                pdf_filename = f"{base_name}.pdf"

                # 复制同名的csv文件
                csv_file_path = os.path.join(input_folder, filename[:-5] + ".csv")
                if os.path.exists(csv_file_path):
                    new_csv_file_path = os.path.join(output_folder, csv_filename)
                    shutil.copy(csv_file_path, new_csv_file_path)
                    print(f"Copied CSV file to: {new_csv_file_path}")

                # 复制同名的pdf文件
                pdf_file_path = os.path.join(input_folder, filename[:-5] + ".pdf")
                if os.path.exists(pdf_file_path):
                    new_pdf_file_path = os.path.join(output_folder, pdf_filename)
                    shutil.copy(pdf_file_path, new_pdf_file_path)
                    print(f"Copied PDF file to: {new_pdf_file_path}")

            except Exception as e:
                print(f"Error processing file {filename}: {e}")


def archive_and_clear_input_folder(input_folder, archive_folder):
    # 确保归档文件夹存在
    os.makedirs(archive_folder, exist_ok=True)

    # 遍历输入文件夹中的所有文件
    for filename in os.listdir(input_folder):
        file_path = os.path.join(input_folder, filename)
        archive_file_path = os.path.join(archive_folder, filename)
        try:
            # 移动文件到归档文件夹
            shutil.move(file_path, archive_file_path)
            print(f"Archived to: {archive_file_path}")
        except Exception as e:
            print(f"Error archiving file {filename}: {e}")


def main():
    input_folder, output_folder, archive_folder = get_config_paths()
    process_files(input_folder, output_folder)
    archive_and_clear_input_folder(input_folder, archive_folder)


if __name__ == "__main__":
    main()
